import json

from PySide6.QtCore import QObject, Slot, Signal
from qframelesswindow.webengine import FramelessWebEngineView
from queue_sqlite.model import MessageItem
from queue_sqlite.scheduler import QueueScheduler


class WebViewQueueSqliteOperations(QObject):
    """
    用于前端调用QueueSqlite的队列操作
    """

    update_queue_state_signal = Signal(dict, str)

    def __init__(
        self,
        webview: FramelessWebEngineView,
        queue_scheduler: QueueScheduler,
        parent=None,
    ):
        super().__init__(parent)
        self.webview = webview
        self.page = self.webview.page()
        self.update_queue_state_signal.connect(self.update_queue_state)
        self.queue_scheduler = queue_scheduler

    @Slot(str, str, result=str)
    def send_message(self, message: str, store_key: str):
        def callback(result: MessageItem):
            print(f"send_message callback: {result}")
            self.update_queue_state_signal.emit(result.to_dict(), store_key)

        self.queue_scheduler.send_message(
            MessageItem.from_dict(json.loads(message)), callback
        )

    def update_queue_state(self, result: dict, store_key: str):
        json_str = json.dumps(result)
        print(f"result: {result}")
        print(f"json_str: {json_str}")
        js_code = f"""
        try {{
            if (typeof window.queueStore.updateQueueData === 'function') {{
                window.queueStore.updateQueueData('{store_key}', {json_str});
            }} else {{
                console.log('updateQueueData function not found');
            }}
        }} catch (error) {{
            console.error('Error in updateQueueData:', error);
        }}
        """
        print(f"执行的JavaScript代码: {js_code}")
        self.page.runJavaScript(js_code)
